using System;

using Gtk;

namespace Gazebo
{
    internal static class Extras
    {
        internal static EventHandler<T> OnMainLoop<T>(EventHandler<T> handler) where T : EventArgs {
            return delegate(object sender, T args) {
                Application.Invoke(delegate {
                    handler(sender, args);
                });
            };
        }
        
        internal static EventHandler OnMainLoop(EventHandler handler) {
            return delegate(object sender, EventArgs args) {
                Application.Invoke(sender, args, handler);
            };
        }
        
        internal static string TrimNewlines(this string str) {
            if (str == null) {
                return null;
            }
            
            if (str.Length == 0) {
                return str;
            }
            
            if (str[0] != '\n' && str[str.Length - 1] != '\n') {
                return str;
            }
            
            char[] buffer = str.ToCharArray();
            
            int start = 0;
            int length = buffer.Length;
            
            for (int i = 0; i < buffer.Length; i++) {
                if (buffer[i] != '\n') {
                    break;
                }
                
                start++;
                length--;
            }
            
            for (int i = buffer.Length - 1; length > 0; i--) {
                if (buffer[i] != '\n') {
                    break;
                }
                
                length--;
            }
            
            return new string(buffer, start, length);
        }
    }
}
